package com.chengyu.core.service.ty.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.chengyu.core.domain.CommonConstant;
import com.chengyu.core.domain.enums.AccountEnums;
import com.chengyu.core.domain.enums.OrderEnums;
import com.chengyu.core.domain.form.CaculateFreightFeeForm;
import com.chengyu.core.domain.form.OrderSearchForm;
import com.chengyu.core.domain.form.TyOrderAddForm;
import com.chengyu.core.domain.result.*;
import com.chengyu.core.entity.CommonPage;
import com.chengyu.core.exception.ServiceException;
import com.chengyu.core.mapper.*;
import com.chengyu.core.model.*;
import com.chengyu.core.service.ReceiptUserOrderService;
import com.chengyu.core.service.config.ConfigOrderService;
import com.chengyu.core.service.funds.MemberAccountLogService;
import com.chengyu.core.service.member.MemberAccountService;
import com.chengyu.core.service.member.MemberAddressService;
import com.chengyu.core.service.member.MemberCouponService;
import com.chengyu.core.service.member.MemberService;
import com.chengyu.core.service.order.OrderCommentService;
import com.chengyu.core.service.schedule.RedisDelayQueueEnum;
import com.chengyu.core.service.schedule.RedisDelayQueueUtil;
import com.chengyu.core.service.ty.TyOrderService;
import com.chengyu.core.util.sms.SmsUtil;
import com.chengyu.core.utils.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.chengyu.core.model.TyOrder;



import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author LeGreen
 * @title 订单
 * @date 2022/4/29
 */
@Slf4j
@Service
public class TyOrderServiceImpl implements TyOrderService {

    @Autowired
    private TyOrderMapper orderMapper;

    @Autowired
    private ConfigOrderService configOrderService;

    @Autowired
    private MemberCouponService memberCouponService;

    @Autowired
    private CommonPayOrderMapper payOrderMapper;


    @Autowired
    private MemberAddressService memberAddressService;
    @Autowired
    private OrderCommentService orderCommentService;

    @Autowired
    private TyOrderCommentMapper orderCommentMapper;
    @Autowired
    private TyOrderRefundMapper orderRefundMapper;
    @Autowired
    private TyQuoteMapper quoteMapper;
    @Autowired
    private RedisDelayQueueUtil redisDelayQueueUtil;

    @Autowired
    private SmsUtil smsUtil;

    @Autowired
    private MemberService memberService;
    @Autowired
    private MemberAccountService memberAccountService;


    @Autowired
    private ReceiptUserOrderService receiptUserOrderService;


    @Autowired
    private MemberAccountLogService memberAccountLogService;





    @Override
    public CommonPage<TyOrderResult> getMyChaseList(Integer memberId, Integer page, Integer pageSize) {
//        TyQuoteExample tyQuoteExample = new TyQuoteExample();
//        tyQuoteExample.createCriteria().andMemberIdEqualTo(memberId);
//        List<TyQuote> tyQuotes = quoteMapper.selectByExample(tyQuoteExample);
//        List<String> orderNos = tyQuotes.stream().map(TyQuote::getOrderNo).collect(Collectors.toList());
//        PageHelper.startPage(page, pageSize);
//        TyOrderExample example = new TyOrderExample();
//        example.createCriteria().andDelIndEqualTo(CommonConstant.NO_INT).andOrderNoIn(orderNos);
//
//
//


        PageHelper.startPage(page, pageSize);
        TyOrderExample example = new TyOrderExample();
//        if (StringUtils.isNotBlank(form.getSort())) {
//            example.setOrderByClause(form.getSort());
//        } else {
            example.setOrderByClause("add_time desc");
//        }

        TyOrderExample.Criteria criteria = example.createCriteria();
        criteria.andDelIndEqualTo(CommonConstant.NO_INT);
//        if (StringUtils.isNotBlank(form.getOrderNo())) {
//            criteria.andOrderNoLike("%" + form.getOrderNo() + "%");
//        }
//        if (form.getMemberId() != null) {
//            criteria.andMemberIdEqualTo(form.getMemberId());
//        }
//        if (form.getShopId() != null) {
//            criteria.andShopIdEqualTo(form.getShopId());
//        }
//        if (StringUtils.isNotBlank(form.getMemberName())) {
//            criteria.andMemberNameLike("%" + form.getMemberName() + "%");
//        }
//        if (form.getStatus() != null) {
//            criteria.andStatusEqualTo(form.getStatus());
//        }
//        if (CollectionUtil.isNotEmpty(form.getStatusList())) {
//            criteria.andStatusIn(form.getStatusList());
//        }
//        if (form.getDateFrom() != null && form.getDateTo() != null) {
//            criteria.andPayTimeBetween(form.getDateFrom(), form.getDateTo());
//        }
//        if (CollectionUtil.isNotEmpty(form.getOrderIdList())) {
//            criteria.andIdIn(form.getOrderIdList());
//        }

        criteria.andMerMemberIdEqualTo(memberId);



        List<TyOrder> list = orderMapper.selectByExample(example);
        PageInfo orderPage = new PageInfo<>(list);
        return CommonPage.restPage(orderPage);

    }

    @Override
    public CommonPage<TyOrderResult> getOrderList(OrderSearchForm form, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        TyOrderExample example = new TyOrderExample();
        if (StringUtils.isNotBlank(form.getSort())) {
            example.setOrderByClause(form.getSort());
        } else {
            example.setOrderByClause("add_time desc");
        }
        TyOrderExample.Criteria criteria = example.createCriteria();
        criteria.andDelIndEqualTo(CommonConstant.NO_INT);
        if (StringUtils.isNotBlank(form.getOrderNo())) {
            criteria.andOrderNoLike("%" + form.getOrderNo() + "%");
        }

        if (form.getNotMemberId()!= null) {
            criteria.andMemberIdNotEqualTo(form.getNotMemberId());
        }
        if (form.getMemberId() != null) {
            criteria.andMemberIdEqualTo(form.getMemberId());
        }

        if (form.getMerMemberId() != null) {
            criteria.andMerMemberIdEqualTo(form.getMerMemberId());
            criteria.andStatusNotEqualTo(OrderEnums.TyOrderStatus.CANCEL.getValue() );
        }
        if (form.getShopId() != null) {
            criteria.andShopIdEqualTo(form.getShopId());
        }
        if (StringUtils.isNotBlank(form.getMemberName())) {
            criteria.andMemberNameLike("%" + form.getMemberName() + "%");
        }
        if (form.getStatus() != null) {
            criteria.andStatusEqualTo(form.getStatus());
        }
        if (CollectionUtil.isNotEmpty(form.getStatusList())) {
            criteria.andStatusIn(form.getStatusList());
        }
        if (form.getDateFrom() != null && form.getDateTo() != null) {
            criteria.andPayTimeBetween(form.getDateFrom(), form.getDateTo());
        }
        if (StrUtil.isNotEmpty(form.getReceiveCity())) {
            criteria.andReceiveCityEqualTo(form.getReceiveCity());
        }
        if (StrUtil.isNotEmpty(form.getCity())) {
            criteria.andSendCityEqualTo(form.getCity());
        }
        if (CollectionUtil.isNotEmpty(form.getOrderIdList())) {
            criteria.andIdIn(form.getOrderIdList());
        }



        List<TyOrder> list = orderMapper.selectByExample(example);
        PageInfo orderPage = new PageInfo<>(list);
        return CommonPage.restPage(orderPage);
    }

    @Override
    public TyOrderResult getOrder(Integer orderId) {
        TyOrderResult orderResult = new TyOrderResult();
        orderResult.setOrder(orderMapper.selectByPrimaryKey(orderId));
        return orderResult;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public TyOrderPayResult addOrder(UmsMember member, UmsMemberAddress addressTo, UmsMemberAddress addressFrom,ReceiptUser receiptUser, TyOrderAddForm addForm) throws ServiceException {
        if (Objects.isNull(addressTo) || Objects.isNull(addressFrom)) {
            throw new ServiceException("order.address");
        }

        ReceiptUser  receiptUserInfo = addForm.getReceiptInfo();


        Date now = DateUtil.date();
        List<CaculateFreightFeeForm> freightFeeFormList = new ArrayList<>();

        TyOrder order = new TyOrder();

        order.setOrderNo("ty"+StringUtils.genOrderNo(member.getId()));



        order.setMemberId(member.getId());
        order.setMemberName(member.getCode());
        order.setMemberNickname(member.getNickname());
        order.setMemberHeadImg(member.getHeadImg());
//        order.setCouponId(addForm.getCouponId());
//        order.setCouponStatus(addForm.getCouponId() == null ? CommonConstant.NO_INT : CommonConstant.YES_INT);
        //校验优惠券
//            BigDecimal couponAmount = memberCouponService.validateCoupon(member, order.getCouponId(), totalPrice, goodsIdList, goodsCateIdList);
        BigDecimal couponAmount = new BigDecimal(0);
        order.setCouponAmount(couponAmount);
        //计算运费
        order.setFreightFee(this.caculateFreightFee(order.getShopId(), addressTo, addressFrom, freightFeeFormList));
        order.setPayPrice(NumberUtil.sub(order.getFreightFee(), couponAmount));
        order.setPrice(NumberUtil.sub(order.getFreightFee(), couponAmount));
        order.setRefundAmount(BigDecimal.ZERO);
        order.setBuyTime(now);
//        order.setStatus(OrderEnums.TyOrderStatus.WAIT_YUYUE.getValue());
        order.setStatus(OrderEnums.TyOrderStatus.WAIT_YUYUE.getValue());
        order.setRefundStatus(OrderEnums.TyRefundStatus.UN_REFUND.getValue());


        order.setPetType(addForm.getPetType());
        order.setPetNumber(addForm.getNumber());
        order.setPetVolume(addForm.getPetVolume());

        order.setPetPhoto(  StringUtils.strip(addForm.getPetPhoto(),","));
        order.setCagePhoto( StringUtils.strip(addForm.getCagePhoto(),","));
        order.setMessage(addForm.getMessage());
        order.setHaulMethod(addForm.getHaulMethod());
        order.setShuttle(addForm.getShuttle());
        if (StringUtils.isNotBlank(addForm.getExpectedTime())) {
            try {
                order.setExpectedTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(addForm.getExpectedTime()));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        order.setCageSize(addForm.getCageSize());
        order.setInsureStatus(addForm.getInsureStatus());
        order.setUrgentStatus(addForm.getUrgentStatus());
        order.setLocateStatus(addForm.getLocateStatus());


        //收货地址
        order.setReceiveName(addressTo.getRealname());
        order.setReceivePhone(addressTo.getPhone());
//        order.setReceiveAddress(addressTo.getProvince() + addressTo.getCity() + addressTo.getArea() + addressTo.getAddress());
        order.setReceiveAddress(addressTo.getCity()+ addressTo.getAddress());
        order.setReceiveLng(addressTo.getLng());
        order.setReceiveLat(addressTo.getLat());
        order.setReceiveCity(addressTo.getCity());
        //发货地址
        order.setSendName(addressFrom.getRealname());
        order.setSendPhone(addressFrom.getPhone());
//        order.setSendAddress(addressFrom.getProvince() + addressFrom.getCity() + addressFrom.getArea() + addressFrom.getAddress());
        order.setSendAddress(addressFrom.getCity() + addressFrom.getAddress());
        order.setSendLng(addressFrom.getLng());
        order.setSendLat(addressFrom.getLat());
        order.setSendCity(addressFrom.getCity());


//        order.setRemark(addForm.getRemark());

        order.setAddTime(now);
        order.setUpdTime(now);
        //判断是新客单还是老客单
        TyOrderExample example = new TyOrderExample();
        example.createCriteria()
                .andMemberIdEqualTo(order.getMemberId())
                .andAddTimeLessThan(new Date()).andStatusIn(CollectionUtil.newArrayList(1, 2, 3));
        order.setNewOrOld(orderMapper.countByExample(example) > 0 ? 1 : 0);





        orderMapper.insertSelective(order);

//        //发票
//        if(receiptUser!=null  &&  receiptUser.getReceiptTitle().length()>0){
//            order.setInvoiceStatus(1);
//            //写入发票数据
//            ReceiptUserOrder receiptUserOrder = new ReceiptUserOrder();
//            BeanUtils.copyProperties(receiptUser, receiptUserOrder);
//            receiptUserOrder.setUid(order.getMemberId());
//            receiptUserOrder.setOrderType(1);
//            receiptUserOrder.setOrderNo(order.getOrderNo());
//
//            receiptUserOrderService.save(receiptUserOrder);
//        }
//        //发票
//        if(form.getReceiptInfo()!=null  && form.getReceiptInfo().getReceiptTitle()!=null &&  form.getReceiptInfo().getReceiptTitle().length()>0){
//            order.setInvoiceStatus(1);
//            //写入发票数据
//            ReceiptUserOrder receiptUserOrder = new ReceiptUserOrder();
//            BeanUtils.copyProperties(form.getReceiptInfo(), receiptUserOrder);
//            receiptUserOrder.setUid(order.getMemberId());
//            receiptUserOrder.setOrderType(1);
//            receiptUserOrder.setOrderNo(order.getOrderNo());
//
//            receiptUserOrderService.save(receiptUserOrder);
//        }


        TyOrderPayResult result = new TyOrderPayResult();
        result.setOrderNo(order.getOrderNo());
        return result;
    }

    /**
     * 计算商品运费
     *
     * @param addressTo
     * @param addressFrom
     * @param freightFeeFormList
     * @return BigDecimal
     * @author LeGreen
     * @date 2022/5/5
     */
    @Override
    public BigDecimal caculateFreightFee(Integer shopId, UmsMemberAddress addressTo, UmsMemberAddress addressFrom, List<CaculateFreightFeeForm> freightFeeFormList) {
        //运费组合策略
        return BigDecimal.ZERO;
    }

    // TODO: 2023/9/29
    private BigDecimal caculatePayPrice() {
        //运费组合策略
        return new BigDecimal(236);
    }


    /**
     * 支付成功
     *
     * @param payOrderNo
     * @throws ServiceException
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void paySus(String payOrderNo) throws ServiceException {


        System.out.println("paySus");
        CommonPayOrderExample payOrderExample = new CommonPayOrderExample();
        payOrderExample.createCriteria().andPayOrderNoEqualTo(payOrderNo).andStatusEqualTo(CommonConstant.WAIT_INT);

//        payOrderExample.createCriteria().andPayOrderNoEqualTo(payOrderNo).andStatusEqualTo(OrderEnums.TyOrderStatus.YUYUE.getValue());
        List<CommonPayOrder> payOrderList = payOrderMapper.selectByExample(payOrderExample);

        TyOrderExample example = new TyOrderExample();
        example.createCriteria().andOrderNoEqualTo(payOrderList.get(0).getOrderSn());
        List<TyOrder> list = orderMapper.selectByExample(example);
//                return CollectionUtil.isNotEmpty(list) ? list.get(0) : null;
        TyOrder tyOrder = CollectionUtil.isNotEmpty(list) ? list.get(0) : null;


        if (CollectionUtil.isNotEmpty(payOrderList)) {
            CommonPayOrder updatePayOrder = new CommonPayOrder();
            updatePayOrder.setId(payOrderList.get(0).getId());
            updatePayOrder.setStatus(CommonConstant.SUS_INT);
            updatePayOrder.setUpdTime(DateUtil.date());
            updatePayOrder.setPayTime(updatePayOrder.getUpdTime());
            payOrderMapper.updateByPrimaryKeySelective(updatePayOrder);

            //支付成功, 更新状态

            if(payOrderList.get(0).getOrderGroup().equals("tyOrderAdd")){
                //追加支付

                if (tyOrder == null || tyOrder.getStatus()!=OrderEnums.TyOrderStatus.PAY.getValue()) {
                    throw new ServiceException("status.error");
                }


                TyOrderExample orderExample = new TyOrderExample();
                orderExample.createCriteria().andOrderNoEqualTo(tyOrder.getOrderNo());


                Date now = DateUtil.date();

                BigDecimal payPrice = tyOrder.getPayPrice();
                payPrice = payPrice.add(payOrderList.get(0).getAmount());

                TyOrder updateOrder = new TyOrder();
                updateOrder.setStatus(OrderEnums.TyOrderStatus.PAY.getValue());
                updateOrder.setUpdTime(DateUtil.date());
                updateOrder.setAddPriceTime(now);

                System.out.println("tyOrder.getAddPrice():"+tyOrder.toString());
                System.out.println("tyOrder.getAddPrice():"+tyOrder.getAddPrice());
                System.out.println("payOrderList.get(0).getAmount():"+payOrderList.get(0).getAmount());




                updateOrder.setAddPrice(  payOrderList.get(0).getAmount().add(tyOrder.getAddPrice()));
                updateOrder.setPayPrice(payPrice);
                updateOrder.setAddPriceStatus(1);
                orderMapper.updateByExampleSelective(updateOrder, orderExample);


            }else   if(payOrderList.get(0).getOrderGroup().equals("tyOrder")){

                if (tyOrder == null || tyOrder.getStatus()>=3) {
                    throw new ServiceException("status.error");
                }

                //订单支付
                TyOrderExample orderExample = new TyOrderExample();

                orderExample.createCriteria().andPayOrderNoEqualTo(payOrderNo).andStatusEqualTo(OrderEnums.TyOrderStatus.YUYUE.getValue());
                //orderExample.createCriteria().andPayOrderNoEqualTo(payOrderNo).andStatusEqualTo(OrderEnums.TyOrderStatus.YUYUE.getValue());

            //            List<TyOrder> orderList = orderMapper.selectByExample(orderExample);


                TyOrder updateOrder = new TyOrder();
                updateOrder.setStatus(OrderEnums.TyOrderStatus.PAY.getValue());
                updateOrder.setUpdTime(DateUtil.date());
                updateOrder.setPayTime(updateOrder.getUpdTime());
                orderMapper.updateByExampleSelective(updateOrder, orderExample);

                //更新优惠券状态
            //            for (TyOrder order : orderList) {
            //                if (order.getCouponStatus() == CommonConstant.YES_INT && order.getCouponId() != null) {
            //                    memberCouponService.useCoupon(order.getCouponId());
            //                }

            //                ChatNotice notice = new ChatNotice();
            //                notice.setTitle("重要! 您有一笔新的订单,请及时发货~");
            //                notice.setContent(JSONUtil.toJsonStr(detailList.get(0)));
            //                notice.setType(MemberRemindEnums.MemberRemindTypes.NEW_ORDER.getType());
            //                chatService.sendNoticeMsg(shop.getMemberId(), JSONUtil.toJsonStr(notice));
            //				memberRemindService.addShopRemind(order.getShopId(), MemberRemindEnums.MemberRemindTypes.NEW_ORDER, "重要! 您有一笔新的订单,请及时发货~");
            //            }


            //            String content = "验证码: "+code+", 如非本人操作, 请忽略本短信。";

                List<TyOrder> orders = orderMapper.selectByExample(orderExample);
                if(CollectionUtil.isNotEmpty(orders)){
                    TyOrder   order  =  orders.get(0);
                    UmsMember merMember = memberService.getMemberById(order.getMerMemberId());

                    String from  = order.getSendAddress();
                    String to  = order.getReceiveCity();;
                    String phone  = merMember.getPhone();
                    String content = "您接的"+from+"到"+to+"订单已付款 ,请您尽快登陆宠易优，点击开始输运";
                    Map<String,String> templateParam = new HashMap<>(16);
                    templateParam.put("from", from);
                    templateParam.put("to", to);
            //                log.info(content);
                    smsUtil.send(phone, String.valueOf(8), templateParam);

                }
            }






        }
    }


    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void confirmOrder(UmsMember member, Integer orderId) throws ServiceException {
        TyOrder order = this.getOrderByMember(member, orderId);
        if (order.getStatus() != OrderEnums.TyOrderStatus.RECEIVED.getValue()) {
            throw new ServiceException("order.confirm");
        }
        this.finishOrder(order);
    }





    public void distributionMoney(TyOrder order, AccountEnums.MemberAccountTypes accountType, String orderNo, BigDecimal amount, String remark, String ip) throws ServiceException{
        // 托运： 10%提点  ，平台得8%,   推荐商家提点 2% ,  商家需要压保证金15个工作日。保证金从交易完成里扣1500，每次扣20%
        // 假设是商家自己推荐的单（不是该商家运输）也就是300的运输价格扣30%  平台得24 元，推荐商家得6 元，扣入保证金里。
        // 如果是商家自己运输的那就是300元的运输价格扣10%手续费平台全得。也就是300-30平台的=270X20%=54元扣在平台作为他的保证金。
        UmsMember merMember = memberService.getMemberById(order.getMerMemberId());


        BigDecimal   totalPrice = order.getPayPrice();
        double bili = 0.1;
        double bili_tjr = 0.2;
        double hzj_max = 1500;

//        if(order.getType().equals(5)){//预约
//            bili  =  0.1;
//            bili_tjr  =  0.07;
//        }else if(order.getType().equals(11)){//卖狗
//            bili  =  0.1;
//            bili_tjr  =  0.05;
//        }else if(order.getType().equals(1)){
//            bili = 0.04;
//            bili_tjr = 0.02;
//        }

//		商城物品提4%


//		商家获取96%
        BigDecimal resultMerchant = totalPrice.multiply(BigDecimal.valueOf((1-bili)));
        resultMerchant = resultMerchant.setScale(2, BigDecimal.ROUND_DOWN);
        //商家获得商品款项
        UmsMemberAccount account  = memberAccountService.getMemberAccount(merMember.getId());
        BigDecimal bjz_t =  resultMerchant.multiply(BigDecimal.valueOf(0.2));
        //商家获得商品款项 resultMerchant  以及自动保证金
        if(account.getBzj().compareTo(BigDecimal.valueOf(hzj_max)) >=0){
            memberAccountLogService.inAccount(merMember, AccountEnums.MemberAccountTypes.ACCOUNT_TY_IN, order.getOrderNo(), resultMerchant, "托运商家交易收款", null);

        }
        else if(account.getBzj().add(bjz_t).compareTo(BigDecimal.valueOf(hzj_max)) <=0){

            memberAccountLogService.inAccount(merMember, AccountEnums.MemberAccountTypes.ACCOUNT_TY_IN, order.getOrderNo(), resultMerchant.subtract(bjz_t), "托运商家交易收款1", null);
            memberAccountLogService.inBzj(merMember, AccountEnums.MemberAccountTypes.ACCOUNT_BZJ_IN, order.getOrderNo(), bjz_t, "托运商家交易收款_自动保证金1", null);

        }
        else if(account.getBzj().add(bjz_t).compareTo(BigDecimal.valueOf(hzj_max)) >0){

            BigDecimal bjz_duo =  account.getBzj().add(bjz_t).subtract(BigDecimal.valueOf(hzj_max));
            BigDecimal bjz_real =  bjz_t.subtract(bjz_duo);
            memberAccountLogService.inAccount(merMember, AccountEnums.MemberAccountTypes.ACCOUNT_TY_IN, order.getOrderNo(), resultMerchant.subtract(bjz_real), "托运商家交易收款2", null);
            memberAccountLogService.inBzj(merMember, AccountEnums.MemberAccountTypes.ACCOUNT_BZJ_IN, order.getOrderNo(), bjz_real, "托运商家交易收款_自动保证金2", null);

        }




        Integer cMemberId = 1;
//		是否有直推
//		shopMember.getTjrId()
        if(merMember.getTjrUid()!=null  &&   merMember.getTjrUid()>0){
            //有推荐人

            BigDecimal result2 = totalPrice.multiply(BigDecimal.valueOf(bili_tjr));
            result2 = result2.setScale(2, BigDecimal.ROUND_DOWN);

            //直推
            UmsMember pMember = memberService.getMemberById(merMember.getTjrUid());
            memberAccountLogService.inAccount(pMember, AccountEnums.MemberAccountTypes.ACCOUNT_BZJ_IN, order.getOrderNo(), result2, AccountEnums.MemberAccountTypes.ACCOUNT_BZJ_IN.getName(), null);


            BigDecimal result3 = totalPrice.multiply(BigDecimal.valueOf(bili-bili_tjr));
            result3 = result3.setScale(2, BigDecimal.ROUND_DOWN);
            //公司
            UmsMember cMember = memberService.getMemberById(cMemberId);
            memberAccountLogService.inAccount(merMember, AccountEnums.MemberAccountTypes.ACCOUNT_BZJ_IN, order.getOrderNo(), result2, AccountEnums.MemberAccountTypes.ACCOUNT_BZJ_IN.getName(), null);


        }else{
            //无推荐人  没直推公司全得

            BigDecimal result = totalPrice.multiply(BigDecimal.valueOf(bili));
            result = result.setScale(2, BigDecimal.ROUND_DOWN);

            log.info("cMemberId>>"+cMemberId);
            UmsMember cMember = memberService.getMemberById(cMemberId);
            memberAccountLogService.inAccount(cMember, AccountEnums.MemberAccountTypes.ACCOUNT_BZJ_IN, order.getOrderNo(), result, "公司_托运交易收款", null);


        }


    }

                /**
                 * 完成订单
                 *
                 * @param order 订单
                 * @throws ServiceException
                 */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void finishOrder(TyOrder order) throws ServiceException {
        ConfigOrder config = configOrderService.getConfigOrder();

        TyOrder updateOrder = new TyOrder();
        updateOrder.setId(order.getId());
        updateOrder.setFinishTime(DateUtil.date());
        updateOrder.setStatus(OrderEnums.TyOrderStatus.FINISHED.getValue());
        updateOrder.setCommentExpiredTime(DateUtil.offsetDay(updateOrder.getFinishTime(), config.getAutoCommentDay()));
        updateOrder.setRefundExpiredTime(DateUtil.offsetDay(updateOrder.getFinishTime(), config.getLastRefundDay()));
        orderMapper.updateByPrimaryKeySelective(updateOrder);

        //商家获得商品款项
        distributionMoney(order,AccountEnums.MemberAccountTypes.ACCOUNT_TRADE_IN, order.getOrderNo(), order.getPayPrice(), "托运交易收款", null);



        //添加自动评价定时器
//        orderCommentService.initComment(detailList);
        redisDelayQueueUtil.addDelayQueue(order.getOrderNo(), updateOrder.getCommentExpiredTime(), RedisDelayQueueEnum.ORDER_AUTO_COMMENT_JOB.getCode());
//		taskTriggerService.addTrigger(OrderAutoCommentJob.class, updateOrder.getCommentExpiredTime(), order.getOrderNo());

        //订单评价提醒
//        UmsShop shop = shopService.getShopById(order.getShopId());
//        TyOrderDetail firstGoods = detailList.get(0);
//        MemberNewsForm newsForm = new MemberNewsForm(MemberNewsEnums.MemberNewsTypes.NEWS_COMMENT_REMIND);
//        newsForm.setShop(shop);
//        newsForm.initTurnParams("orderId", order.getId().toString());
//        newsForm.replace("#goodsName#", firstGoods.getGoodsName());
//        newsForm.setImg(firstGoods.getGoodsMainImg());
//        memberNewsService.addMemberNews(member, newsForm);

        //订单完成消息
//        newsForm = new MemberNewsForm(MemberNewsEnums.MemberNewsTypes.NEWS_FINISH_ORDER);
//        newsForm.setShop(shopService.getShopById(order.getShopId()));
//        newsForm.initTurnParams("orderId", order.getId().toString());
//        newsForm.replace("#goodsName#", firstGoods.getGoodsName());
//        newsForm.setImg(firstGoods.getGoodsMainImg());
//        memberNewsService.addMemberNews(member, newsForm);
    }


    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void updateOrderAddress(UmsMember member, Integer orderId, Integer addressId) throws ServiceException {
        TyOrder order = this.getOrderByMember(member, orderId);
        if (order.getStatus() != OrderEnums.TyOrderStatus.PAY.getValue()) {
            throw new ServiceException("order.edit.address");
        }

        UmsMemberAddress address = memberAddressService.getAddressById(addressId);
        TyOrder updateOrder = new TyOrder();
        updateOrder.setId(orderId);
        updateOrder.setReceiveName(address.getRealname());
        updateOrder.setReceivePhone(address.getPhone());
        updateOrder.setReceiveAddress(address.getProvince() + address.getCity() + address.getArea() + address.getAddress());
        updateOrder.setReceiveLng(address.getLng());
        updateOrder.setReceiveLat(address.getLat());
        updateOrder.setUpdTime(DateUtil.date());
        orderMapper.updateByPrimaryKeySelective(updateOrder);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void cancelOrder(UmsMember member, Integer orderId) throws ServiceException {
        TyOrder order = this.getOrderByMember(member, orderId);
        if (order.getStatus() >= OrderEnums.TyOrderStatus.RECEIVE.getValue()) {
            throw new ServiceException("已发货 不能取消");
        }
        //取消订单并恢复库存
        this.cancelOrderAndAddStock(orderId);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void starttransport(UmsMember member, Integer orderId) throws ServiceException {
        TyOrder order = this.getOrderByMerMember(member, orderId);
        if (order.getStatus() != OrderEnums.TyOrderStatus.PAY.getValue()) {
            throw new ServiceException("没有付款");
        }
        this.starttransport(orderId);
    }

    private void starttransport(Integer orderId) {
        TyOrder updateOrder = new TyOrder();
        updateOrder.setId(orderId);
        updateOrder.setStatus(OrderEnums.TyOrderStatus.RECEIVE.getValue());
        updateOrder.setUpdTime(DateUtil.date());
        orderMapper.updateByPrimaryKeySelective(updateOrder);
    }



    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void endtransport(UmsMember member, Integer orderId) throws ServiceException {
        TyOrder order = this.getOrderByMerMember(member, orderId);
        if (order.getStatus() != OrderEnums.TyOrderStatus.RECEIVE.getValue()) {
            throw new ServiceException("没有发货");
        }
        this.endtransport(orderId);
    }

    private void endtransport(Integer orderId) {
        TyOrder updateOrder = new TyOrder();
        updateOrder.setId(orderId);
        updateOrder.setStatus(OrderEnums.TyOrderStatus.RECEIVED.getValue());
        updateOrder.setUpdTime(DateUtil.date());
        orderMapper.updateByPrimaryKeySelective(updateOrder);
    }



    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void deleteOrder(UmsMember member, Integer orderId) throws ServiceException {
        TyOrder order = this.getOrderByMember(member, orderId);
        if (order.getStatus() != OrderEnums.TyOrderStatus.CANCEL.getValue()) {
            throw new ServiceException("order.cancel.delete");
        }
        TyOrder updateOrder = new TyOrder();
        updateOrder.setId(order.getId());
        updateOrder.setDelInd(CommonConstant.YES_INT);
        updateOrder.setUpdTime(DateUtil.date());
        orderMapper.updateByPrimaryKeySelective(updateOrder);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void autoCancelOrder(String payOrderNo) {
        CommonPayOrderExample payOrderExample = new CommonPayOrderExample();
        payOrderExample.createCriteria().andPayOrderNoEqualTo(payOrderNo).andStatusEqualTo(CommonConstant.WAIT_INT);
        CommonPayOrder updatePayOrder = new CommonPayOrder();
        updatePayOrder.setStatus(CommonConstant.FAIL_INT);
        updatePayOrder.setUpdTime(DateUtil.date());
        payOrderMapper.updateByExampleSelective(updatePayOrder, payOrderExample);

        TyOrderExample orderExample = new TyOrderExample();
        orderExample.createCriteria().andPayOrderNoEqualTo(payOrderNo).andStatusEqualTo(OrderEnums.TyOrderStatus.YUYUE.getValue());

        TyOrder updateOrder = new TyOrder();


        //超时付款   设置给订单发布 未接单的的状态
        updateOrder.setStatus(OrderEnums.TyOrderStatus.WAIT_YUYUE.getValue());
        updateOrder.setMemberId(0);


        updateOrder.setUpdTime(DateUtil.date());
        orderMapper.updateByExampleSelective(updateOrder, orderExample);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void autoFinishOrder(String orderNo) throws ServiceException {
        TyOrderExample example = new TyOrderExample();
        example.createCriteria().andOrderNoEqualTo(orderNo);
        List<TyOrder> list = orderMapper.selectByExample(example);
        if (CollectionUtil.isNotEmpty(list)) {
            TyOrder order = list.get(0);
            if (order.getStatus() == OrderEnums.TyOrderStatus.RECEIVE.getValue()) {
                //自动确认收货
                this.finishOrder(order);
            }
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void deleteOrderByAdmin(List<Integer> idList) {
        TyOrderExample example = new TyOrderExample();
        example.createCriteria().andIdIn(idList);
        TyOrder updateOrder = new TyOrder();
        updateOrder.setDelInd(CommonConstant.YES_INT);
        orderMapper.updateByExampleSelective(updateOrder, example);
    }


    @Override
    public Map<String, Object> count(Integer memberId) {
        Map<String, Object> result = new HashMap<>();
        //统计待发货，待收货，待评价，退款数量
        TyOrderExample example = new TyOrderExample();
        example.createCriteria().andMemberIdEqualTo(memberId).andStatusEqualTo(OrderEnums.TyOrderStatus.PAY.getValue());
        result.put("waitDeliveryNum", orderMapper.countByExample(example));
        example = new TyOrderExample();
        example.createCriteria().andMemberIdEqualTo(memberId).andStatusEqualTo(OrderEnums.TyOrderStatus.RECEIVE.getValue());
        result.put("waitReceiveNum", orderMapper.countByExample(example));

        TyOrderCommentExample commentExample = new TyOrderCommentExample();
        commentExample.createCriteria().andMemberIdEqualTo(memberId).andStatusEqualTo(CommonConstant.NO_INT);
        result.put("waitCommentNum", orderCommentMapper.countByExample(commentExample));

        TyOrderRefundExample refundExample = new TyOrderRefundExample();
        refundExample.createCriteria().andMemberIdEqualTo(memberId).andStatusIn(CollectionUtil.newArrayList(
                OrderEnums.RefundDetailStatus.APPLY.getValue(),
                OrderEnums.RefundDetailStatus.WAIT_BUYER_RETURN.getValue(),
                OrderEnums.RefundDetailStatus.BUYER_RETURNED.getValue(),
                OrderEnums.RefundDetailStatus.SERVICE_IN.getValue()));
        result.put("refundNum", orderRefundMapper.countByExample(refundExample));
        return result;
    }

    @Override
    public CommonPayOrder getPayOrder(String payOrderNo) {
        CommonPayOrderExample example = new CommonPayOrderExample();
        example.createCriteria().andPayOrderNoEqualTo(payOrderNo);
        List<CommonPayOrder> list = payOrderMapper.selectByExample(example);
        return CollectionUtil.isNotEmpty(list) ? list.get(0) : null;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void updateOrderPaymethod(String payOrderNo, String payMethod, String payChannel) {
        CommonPayOrderExample example = new CommonPayOrderExample();
        example.createCriteria().andPayOrderNoEqualTo(payOrderNo);
        CommonPayOrder updatePayOrder = new CommonPayOrder();
        updatePayOrder.setPayMethod(payMethod);
        updatePayOrder.setPayChannel(payChannel);
        payOrderMapper.updateByExampleSelective(updatePayOrder, example);

        TyOrderExample orderExample = new TyOrderExample();
        orderExample.createCriteria().andPayOrderNoEqualTo(payOrderNo);
        TyOrder updateOrder = new TyOrder();
        updateOrder.setPayMethod(payMethod);
        updateOrder.setPayChannel(payChannel);
        orderMapper.updateByExampleSelective(updateOrder, orderExample);
    }

    @Override
    public TyOrder getOrderById(Integer orderId) {

        return orderMapper.selectByPrimaryKey(orderId);



    }
//    @Override
//    public TyOrderResult getOrderById(Integer orderId) {
//        TyOrderResult orderResult = new TyOrderResult();
//        orderResult.setOrder(orderMapper.selectByPrimaryKey(orderId));
//        return orderResult;
//    }




    @Override
    public TyOrder getOrderByOrderNo(String orderNo) {
        TyOrderExample example = new TyOrderExample();
        example.createCriteria().andOrderNoEqualTo(orderNo);
        List<TyOrder> list = orderMapper.selectByExample(example);
        return CollectionUtil.isNotEmpty(list) ? list.get(0) : null;
    }

    @Override
    public TyOrder getOrderByPayOrderNo(String payOrderNo) {
        TyOrderExample example = new TyOrderExample();
        example.createCriteria().andPayOrderNoEqualTo(payOrderNo);
        List<TyOrder> list = orderMapper.selectByExample(example);
        return CollectionUtil.isNotEmpty(list) ? list.get(0) : null;
    }


    private void cancelOrderAndAddStock(Integer orderId) {
        TyOrder updateOrder = new TyOrder();
        updateOrder.setId(orderId);
        updateOrder.setStatus(OrderEnums.TyOrderStatus.CANCEL.getValue());
        updateOrder.setUpdTime(DateUtil.date());
        orderMapper.updateByPrimaryKeySelective(updateOrder);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void cancelAndRefundOrderSus(TyOrder order) {
        if (CollectionUtil.contains(CollectionUtil.newArrayList(
                OrderEnums.TyOrderStatus.PAY.getValue(),
                OrderEnums.TyOrderStatus.RECEIVE.getValue(),
                OrderEnums.TyOrderStatus.FINISHED.getValue()
        ), order.getStatus())) {
            this.cancelOrderAndAddStock(order.getId());
        }
    }

    /**
     * 获取报价
     *
     * @param orderNo
     * @return
     */
    @Override
    public List<TyService> getTyService(String orderNo) {
        List<TyService> list = new ArrayList<>();
        list.add(new TyService("商务快车1", 1, "大体型宠物点对点服务，客制化需求出行，非独立包车1。", new BigDecimal(126), 4));
        list.add(new TyService("商务快车2", 2, "大体型宠物点对点服务，客制化需求出行，非独立包车3。", new BigDecimal(226), 4));
        list.add(new TyService("商务快车3", 3, "大体型宠物点对点服务，客制化需求出行，非独立包车42。", new BigDecimal(326), 4));
        list.add(new TyService("商务快车4", 4, "大体型宠物点对点服务，客制化需求出行，非独立包车4。", new BigDecimal(426), 4));
        return list;
    }

    @Override
    public TyServiceResult selectTyService(UmsMember member, String orderNo, Integer type) throws ServiceException {
        //生成支付订单
        ConfigOrder orderConfig = configOrderService.getConfigOrder();
        Date now = DateUtil.date();


        TyOrderExample example = new TyOrderExample();
        example.createCriteria().andOrderNoEqualTo(orderNo);
        List<TyOrder> orders = orderMapper.selectByExample(example);
        if (CollectionUtil.isEmpty(orders)) {
            throw new ServiceException("订单不存在");
        }


        TyOrder updateOrder = new TyOrder();
        updateOrder.setId(orders.get(0).getId());
        updateOrder.setStatus(OrderEnums.TyOrderStatus.YUYUE.getValue());
        orderMapper.updateByPrimaryKeySelective(updateOrder);


        TyServiceResult result = new TyServiceResult();
        result.setOrderNo(orderNo);
        return result;
    }


    private BigDecimal getQutoPrice(TyQuote tyQuote ,Integer  priceId) {
        BigDecimal payAmount ;
        switch (priceId) {
            case 1:
                payAmount = tyQuote.getPrice();
               break;
            case 2:
                payAmount = tyQuote.getPrice1();
                break;
            case 3:
                payAmount = tyQuote.getPrice2();
                break;
            case 4:
                payAmount = tyQuote.getPrice3();
                break;
            case 5:
                payAmount = tyQuote.getPrice4();
                break;
            case 6:
                payAmount = tyQuote.getPrice5();
                break;
//            default:
//                语句n;
//                break;
            default:
                throw new IllegalStateException("Unexpected value: " + priceId);
        }
        return payAmount;
    }



        @Override
    public TyPayResult createPay(UmsMember member,Integer quoteId ,Integer  priceId) throws ServiceException{


        System.out.println( "createtyPay-----------------------------------------------------") ;
        TyQuote tyQuote = quoteMapper.selectByPrimaryKey(quoteId);
        if(tyQuote==null){
            throw new ServiceException("报价信息不存在");
        }
        //生成支付订单
        ConfigOrder orderConfig = configOrderService.getConfigOrder();
        Date now = DateUtil.date();

//        System.out.println( quoteId) ;
//        System.out.println( priceId);

        TyOrderExample example = new TyOrderExample();
        example.createCriteria().andOrderNoEqualTo(tyQuote.getOrderNo());
        List<TyOrder> orders = orderMapper.selectByExample(example);
        if (CollectionUtil.isEmpty(orders)) {
            throw new ServiceException("订单不存在");
        }

        if(!orders.get(0).getStatus().equals(OrderEnums.TyOrderStatus.WAIT_YUYUE.getValue())){
            throw new ServiceException("订单已生成！不能重读选择创建");
        }
//            orders.get   OrderEnums.TyOrderStatus.YUYUE.getValue().eq
//            if ( OrderEnums.TyOrderStatus.YUYUE.getValue()) {
//                throw new ServiceException("订单不存在");
//            }
//            OrderEnums.TyOrderStatus.YUYUE.getValue());


        BigDecimal payAmount = BigDecimal.ZERO;
        CommonPayOrder payOrder = new CommonPayOrder();
        payOrder.setType(1);
        payOrder.setOrderGroup("tyOrder");
        payOrder.setPayOrderNo("ty_"+StringUtils.genTradeNo(member.getId()));
        payOrder.setMemberId(member.getId());
        payOrder.setMemberName(member.getNickname());
        payOrder.setAddTime(now);
        payOrder.setUpdTime(now);
        payOrder.setPayEndTime(DateUtil.offsetMinute(now, orderConfig.getAutoCancelMinutes()));
        payOrder.setStatus(CommonConstant.WAIT_INT);

         payOrder.setOrderSn(orders.get(0).getOrderNo());

        TyOrder updateOrder = new TyOrder();
        updateOrder.setId(orders.get(0).getId());
        updateOrder.setPayEndTime(payOrder.getPayEndTime());
        updateOrder.setPayOrderNo(payOrder.getPayOrderNo());


        updateOrder.setPayPrice(getQutoPrice(tyQuote,priceId));
        updateOrder.setPrice(getQutoPrice(tyQuote,priceId));
        //updateOrder.setHaulMethod(priceId);
        updateOrder.setHaulMethodConfirm(priceId);

//        updateOrder.setPayPrice(caculatePayPrice());
        updateOrder.setStatus(OrderEnums.TyOrderStatus.YUYUE.getValue());
        updateOrder.setShopId(tyQuote.getShopId());
        updateOrder.setShopName(tyQuote.getName());
        updateOrder.setShopLogo(tyQuote.getLogo());

//            System.out.println( "接任务的商家用户id-----------------------------------------------------") ;
//            System.out.println( tyQuote.getMemberId()) ;

        //接任务的商家用户id
        updateOrder.setMerMemberId(tyQuote.getMemberId());

        orderMapper.updateByPrimaryKeySelective(updateOrder);
//        System.out.println( payAmount) ;
//        System.out.println(  updateOrder.getPayPrice());


//        //应该支付的价格
        payAmount = NumberUtil.add(payAmount, updateOrder.getPayPrice());

        payOrder.setAmount(payAmount);
        payOrderMapper.insertSelective(payOrder);

        //超时未支付自动取消
         redisDelayQueueUtil.addDelayQueue(payOrder.getPayOrderNo(), payOrder.getPayEndTime(), RedisDelayQueueEnum.TY_ORDER_AUTO_CANCEL_JOB.getCode());


        TyPayResult result = new TyPayResult();
        result.setAmount(payOrder.getAmount());
        result.setPayOrderNo(payOrder.getPayOrderNo());
        result.setOrderNo(tyQuote.getOrderNo());
        return result;
    }


    @Override
    public TyPayResult createPay(UmsMember member, String orderNo, Integer quoteId) throws ServiceException {
        TyQuote tyQuote = quoteMapper.selectByPrimaryKey(quoteId);
        //生成支付订单
        ConfigOrder orderConfig = configOrderService.getConfigOrder();
        Date now = DateUtil.date();


        TyOrderExample example = new TyOrderExample();
        example.createCriteria().andOrderNoEqualTo(orderNo);
        List<TyOrder> orders = orderMapper.selectByExample(example);
        if (CollectionUtil.isEmpty(orders)) {
            throw new ServiceException("订单不存在");
        }

        BigDecimal payAmount = BigDecimal.ZERO;
        CommonPayOrder payOrder = new CommonPayOrder();
        payOrder.setPayOrderNo(StringUtils.genTradeNo(member.getId()));
        payOrder.setType(1);
        payOrder.setMemberId(member.getId());
        payOrder.setMemberName(member.getNickname());
        payOrder.setAddTime(now);
        payOrder.setUpdTime(now);
        payOrder.setPayEndTime(DateUtil.offsetMinute(now, orderConfig.getAutoCancelMinutes()));
        payOrder.setStatus(CommonConstant.WAIT_INT);


        TyOrder updateOrder = new TyOrder();
        updateOrder.setId(orders.get(0).getId());
        updateOrder.setPayEndTime(payOrder.getPayEndTime());
        updateOrder.setPayOrderNo(payOrder.getPayOrderNo());
        updateOrder.setPayPrice(caculatePayPrice());
        updateOrder.setPrice(caculatePayPrice());
//        updateOrder.setStatus(OrderEnums.TyOrderStatus.PAY.getValue());
//        updateOrder.setShopId(tyQuote.getShopId());
//        updateOrder.setShopLogo(tyQuote.getName());
//        updateOrder.setShopLogo(tyQuote.getLogo());
        orderMapper.updateByPrimaryKeySelective(updateOrder);


        payAmount = NumberUtil.add(payAmount, updateOrder.getPayPrice());

        payOrder.setAmount(payAmount);

        payOrder.setOrderGroup("tyOrder");
        payOrder.setOrderSn(orders.get(0).getOrderNo());


        payOrderMapper.insertSelective(payOrder);

        //超时未支付自动取消
//        redisDelayQueueUtil.addDelayQueue(payOrder.getPayOrderNo(), payOrder.getPayEndTime(), RedisDelayQueueEnum.ORDER_AUTO_CANCEL_JOB.getCode());
//		taskTriggerService.addTrigger(OrderAutoCancelJob.class, payOrder.getPayEndTime(), payOrder.getPayOrderNo());





        TyPayResult result = new TyPayResult();
        result.setAmount(payOrder.getAmount());
        result.setPayOrderNo(payOrder.getPayOrderNo());
        result.setOrderNo(orderNo);
        return result;
    }


    @Override
    public TyPayResult createAddPay(UmsMember member, TyOrder tyOrder,BigDecimal amount) throws ServiceException {
//        TyQuote tyQuote = quoteMapper.selectByPrimaryKey(quoteId);
        //生成支付订单
        ConfigOrder orderConfig = configOrderService.getConfigOrder();
        Date now = DateUtil.date();


        TyOrderExample example = new TyOrderExample();
        example.createCriteria().andOrderNoEqualTo(tyOrder.getOrderNo());
        List<TyOrder> orders = orderMapper.selectByExample(example);
        if (CollectionUtil.isEmpty(orders)) {
            throw new ServiceException("订单不存在");
        }


//
//        if(!tyOrder.getStatus().equals(OrderEnums.TyOrderStatus.WAIT_YUYUE.getValue())){
//            throw new ServiceException("订单已生成！不能重读选择创建");
//        }
//            orders.get   OrderEnums.TyOrderStatus.YUYUE.getValue().eq
//            if ( OrderEnums.TyOrderStatus.YUYUE.getValue()) {
//                throw new ServiceException("订单不存在");
//            }
//            OrderEnums.TyOrderStatus.YUYUE.getValue());


        BigDecimal payAmount = BigDecimal.ZERO;
        CommonPayOrder payOrder = new CommonPayOrder();
        payOrder.setType(2);
        payOrder.setOrderGroup("tyOrderAdd");
        payOrder.setPayOrderNo("ty_"+StringUtils.genTradeNo(member.getId()));
        payOrder.setMemberId(member.getId());
        payOrder.setMemberName(member.getNickname());
        payOrder.setAddTime(now);
        payOrder.setUpdTime(now);
        payOrder.setPayEndTime(DateUtil.offsetMinute(now, orderConfig.getAutoCancelMinutes()));
        payOrder.setStatus(CommonConstant.WAIT_INT);

        payOrder.setOrderSn(tyOrder.getOrderNo());



//        //应该支付的价格
        payOrder.setAmount(amount);
        payOrderMapper.insertSelective(payOrder);

        //超时未支付自动取消
        redisDelayQueueUtil.addDelayQueue(payOrder.getPayOrderNo(), payOrder.getPayEndTime(), RedisDelayQueueEnum.TY_ORDER_AUTO_CANCEL_JOB.getCode());


        TyPayResult result = new TyPayResult();
        result.setAmount(payOrder.getAmount());
        result.setPayOrderNo(payOrder.getPayOrderNo());
        result.setOrderNo(tyOrder.getOrderNo());
        return result;
    }


    /**
     * 根据用户获取订单
     *
     * @param member
     * @param orderId
     * @return TyOrder
     * @author LeGreen
     * @date 2022/5/5
     */
    private TyOrder getOrderByMember(UmsMember member, Integer orderId) throws ServiceException {
        TyOrderExample example = new TyOrderExample();
        example.createCriteria().andMemberIdEqualTo(member.getId()).andIdEqualTo(orderId);
        List<TyOrder> list = orderMapper.selectByExample(example);
        if (CollectionUtil.isEmpty(list)) {
            throw new ServiceException("order.notexist");
        }
        return list.get(0);
    }

    private TyOrder getOrderByMerMember(UmsMember member, Integer orderId) throws ServiceException {
        TyOrderExample example = new TyOrderExample();
        example.createCriteria().andMerMemberIdEqualTo(member.getId()).andIdEqualTo(orderId);
        List<TyOrder> list = orderMapper.selectByExample(example);
        if (CollectionUtil.isEmpty(list)) {
            throw new ServiceException("order.notexist");
        }
        return list.get(0);
    }

}
